<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>canvas图片自动缩放动画</title>
	</head>
	<body>
		<canvas id="circle" width="500px" height="500px">
			Your browser does not support the HTML5 canvas tag.
		</canvas>
	</body>
	<script>
		/**
		 * 计算图片左上角在canvas上的坐标
		 * @param {Object} canvasHeight 画布的高
		 * @param {Object} canvasWidth 画布的宽
		 * @param {Object} imgHeight 图片的高
		 * @param {Object} imgWidth 图片的宽
		 */
		var leftXY = function(canvasHeight, canvasWidth, imgHeight, imgWidth){
			return {
				x:canvasWidth/2-imgWidth/2,
				y:canvasHeight/2-imgHeight/2
			}
		}
		/**
		 * 缩放图片的方法
		 */
		var scaleImage = function(){
			scale = index;
			cxt.clearRect(0, 0, 500, 500);
			var height = scale * 50;
			var width = scale * 50;
			
			left = leftXY(500, 500, width, height);
			
			cxt.drawImage(img, left.x, left.y, width, height);
			timmer = setTimeout('scaleImage()', 100);
			
			if(addFlag){
				index+=0.1;
			}else{
				index-=0.1;
			}
			
			if(index>5){
				addFlag = false;
			}else if(index<1){
				addFlag = true;
			}
		}
		
		/**
		 * 初始化图片并执行定时任务的方法
		 * @param {Object} 
		 */
		var init = function(cxt){
			var img = new Image();
			img.src="img/circle.png";
			img.height="50px";
			img.width="50px";
			img.onload = function(){
				timmer = setTimeout('scaleImage()', 100);
			}
		}
		
		var cxt = document.getElementById("circle").getContext("2d");
		var index = 0;
		var addFlag = true;
		var canvas = {width:500,height:500};
		var img = {width:50,height:50};
		var timmer = "";
		
		//调用执行定时任务
		init(cxt);
	</script>
</html>
